package com.xcf.center.server;

import com.alibaba.fastjson.JSON;
import com.xcf.center.ServerMeta;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.zookeeper.CreateMode;

public class ZookeeperRegister implements IRegister {

    private final RegisterConfig config;

    private CuratorFramework zookeeperClient;

    public ZookeeperRegister() {
        this(new RegisterConfig());
    }

    public ZookeeperRegister(RegisterConfig config) {
        if (null == config) {
            throw new NullPointerException("config can't null");
        }
        this.config = config;
    }

    public void init() {
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(config.getRegisterConfig().getConnectSting()) // server地址
                .sessionTimeoutMs(config.getRegisterConfig().getSessionTimeOut()) // 会话超时时间
                .connectionTimeoutMs(config.getRegisterConfig().getConnectTimeOut()) // 连接超时时间
                .retryPolicy(config.getRegisterConfig().getRetryPolicy()) // 重试策略
                .namespace(config.getNameSpace()) // ⽴命名空间 /base
                .build(); //
        client.start();
        System.out.println("Zookeeper session established.");
        zookeeperClient = client;
    }

    private void validateClient() {
        if (null == zookeeperClient) {
            throw new NullPointerException("Zookeeper client not init, please init it.");
        }
    }

    /**
     * /nameSpace/serverName01
     *           /serverName02
     *           /..N
     * @param serverMeta
     * @throws Exception
     */
    @Override
    public void register(ServerMeta serverMeta) throws Exception {
        this.validateClient();
        String uniqueName = serverMeta.getUniqueName();
        if (uniqueName.indexOf("/") != 0) {
            uniqueName = "/" + uniqueName;
        }
        String json = JSON.toJSONString(serverMeta);
        zookeeperClient.create()
                .withMode(CreateMode.EPHEMERAL)
                .forPath(uniqueName, json.getBytes());
    }
}
